package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author atguigu-mqx
 */
@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private PaymentService paymentService;

    @Override
    public String createAlipay(Long orderId) throws AlipayApiException {

        //  根据orderId 来获取数据
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);

        //  生成二维码的时候，判断当前订单是否已经产生了支付信息{redis 对应的订单Id 的状态！}！  return "订单已经有了支付信息，不能重复支付!"
        //  盘订单状态！
        if ("CLOSED".equals(orderInfo.getOrderStatus()) || "PAID".equals(orderInfo.getOrderStatus())) {
            return "订单已关闭或订单已支付，请重新下单！";
        }
        //  保存交易记录
        paymentService.savePaymentInfo(orderInfo, PaymentType.ALIPAY.name());

        //  生成 alipayClient 对象，为了后续使用方便，我们需要将alipayClient 注入到spring 容器中！
        //  AlipayClient alipayClient =  new DefaultAlipayClient( "https://openapi.alipay.com/gateway.do" , APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);  //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); //创建API对应的request
        //  同步回调
        //  https://www.domain.com/CallBack/return_url?out_trade_no=ATGUIGU1641278115977548&version=1.0&app_id=2021001163617452&charset=utf-8&sign_type=RSA2&trade_no=2022010422001456601443616453&auth_app_id=2021001163617452&timestamp=2022-01-04%2014:35:40&seller_id=2088831489324244&method=alipay.trade.page.pay.return&total_amount=0.01&sign=Uz5la/wal5tV+6kGEr1UsHowTuTWlIJZcgQlQtNRJs7lF/Y/nfJS9UsURt9CdBwVAjvYZHpFq8hjJvuaW8m7r1rtIuVnOrOZRv8aXK7wjf7omSyZeYxATGDCzICxJEV5IB7IwAF5JBHXfLOZjZpuGa9/a5g40atTg89CkJXoaGrcFUQo0EZu5Z+c9aeXbIZ5P3Za8++MedlCA8ZVH5YbChXeF+28eSVPGN63F0/i0G6GCp4C0sPA4NNfGGpliWTW3evfdWYFfLy02C4SyI6GJFYL74V9c35gxjnHwQj3Qe8+Sqo1QXFtLrZBYt/5gH42tLnNvAG4bDOVX81j0x2uLQ==
        alipayRequest.setReturnUrl(AlipayConfig.return_payment_url);
        //  异步回调
        alipayRequest.setNotifyUrl(AlipayConfig.notify_payment_url); //在公共参数中设置回跳和通知地址
        //  转换：

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_no", orderInfo.getOutTradeNo());
        jsonObject.put("product_code", "FAST_INSTANT_TRADE_PAY");
        //  jsonObject.put("total_amount",orderInfo.getTotalAmount());
        jsonObject.put("total_amount", "0.01");
        jsonObject.put("subject", orderInfo.getTradeBody());
        //  绝对超时时间：yyyy-MM-dd HH:mm:ss
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 10);
        jsonObject.put("time_expire", simpleDateFormat.format(calendar.getTime()));
        alipayRequest.setBizContent(jsonObject.toJSONString());
        //  返回！
        return alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单

    }

    @Override
    public Boolean refund(Long orderId) {
        //  根据orderId 来获取数据
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);

        //  支付的情况下！
        //        if (!"PAID".equals(orderInfo.getOrderStatus())){
        //            return false;
        //        }
        //  调用退款接口：
        //  AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        //  bizContent.put("trade_no", "2021081722001419121412730660");
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        bizContent.put("refund_amount", 0.01);
        bizContent.put("out_request_no", "HZ01RF001");

        //// 返回参数选项，按需传入
        //JSONArray queryOptions = new JSONArray();
        //queryOptions.add("refund_detail_item_list");
        //bizContent.put("query_options", queryOptions);

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (response.isSuccess()) {
            System.out.println("调用成功");
            //  更改订单状态！ CLOSED
            PaymentInfo paymentInfo = new PaymentInfo();
            paymentInfo.setPaymentStatus(PaymentStatus.CLOSED.name());
            paymentService.updatePaymentInfo(orderInfo.getOutTradeNo(), PaymentType.ALIPAY.name(), paymentInfo);
            return true;
        } else {
            System.out.println("调用失败");
            return false;
        }
    }

    @Override
    public Boolean closePay(Long orderId) {
        //  根据订单Id 来获取orderInfo 数据！
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);

        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toString());

        AlipayTradeCloseResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (response.isSuccess()) {
            System.out.println("调用成功");
            return true;
        } else {
            System.out.println("调用失败");
            return false;
        }
    }

    @Override
    public Boolean checkPayment(Long orderId) {
        //  根据订单Id 来获取orderInfo 数据！
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);

        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toString());

        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            return true;
        } else {
            System.out.println("调用失败");
            return false;
        }
    }
}
